<?php

namespace App\Models;
use phpDocumentor\Reflection\Types\Integer;
use Response;

/**
 * App\Models\Article
 *
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Article filter($filters)
 * @mixin \Eloquent
 */
class Article extends BaseModel
{
    //状态类型
    const STATE_DELETED = 0;
    const STATE_UNPUBLISHED = 1;
    const STATE_CANCELED = 2;
    const STATE_CHECKED = 3;
    const STATE_PUBLISHED = 9;
    const STATES = [
        self::STATE_UNPUBLISHED => '未发布',
        self::STATE_CANCELED => '被撤回',
        self::STATE_CHECKED => '已审核',
        self::STATE_PUBLISHED => '已发布',
        self::STATE_DELETED => '已删除',
    ];

    const TAG_HOME = '首页';
    const TAG_TOP = '置顶';
    const TAG_HOT = 'HOT';



    protected $fillable = [
        'category_id',
        'title',
        'list_image_url',
        'tags',
        'summary',
        'content',
        'author',
        'source',
        'sort',
        'state',
        'published_at',
    ];

    public function scopeFilter($query, $filters)
    {
        empty($filters['id']) ?: $query->where('id', $filters['id']);
        empty($filters['category_id']) ?: $query->where('category_id', $filters['category_id']);
        empty($filters['title']) ?: $query->where('title','like', '%' . $filters['title'] . '%');
        empty($filters['start_date']) ?: $query->where('created_at', '>=', $filters['start_date']);
        empty($filters['end_date']) ?: $query->where('created_at', '<=', $filters['end_date']);
        empty($filters['state']) ?: $query->where('state', $filters['state']);
    }

    /**
     * 更新值为0/1的字段
     *
     * @param $id
     * @param $field
     * @return bool
     */
    public static function updateField($id, $field){
        if(empty($id) || empty($field)){
            return false;
        }
        $model = self::find($id);
        if(! isset($model->$field)) {
            return false;
        }
        if ($model->$field == 1) {
            $model->$field = 0;
        } else {
            $model->$field = 1;
        }
        return $model->save();
    }

    /**
     * 批量更新状态
     *
     * @param array $ids
     * @param $state
     * @return bool
     */
    public static function updateState(array $ids, $state)
    {
        $flag = true;
        $models = self::whereIn('id', $ids)->get();
        foreach ($models as $model) {
            if ($state == self::STATE_PUBLISHED) {
                $model->published_at = date('Y-m-d H:i:s');
            }
            $model->state = $state;
            $flag = $model->save();
            if ($flag) {
                if($state == self::STATE_DELETED) {
                    $model->delete();
                }
            } else {
                break;
            }
        }
        return $flag;
    }

    public static function sort()
    {
        $select_id = request('select_id');
        $place_id = request('place_id');
        $move_down = request('move_down');

        $select = self::find($select_id);
        $place = self::find($place_id);

        if (empty($select) || empty($place)) {
            return Response::json([
                'code' => 404,
                'message' => 'ID不存在',
            ]);
        }

        try {
            if ($move_down) {
                //下移
                $select->sort = $place->sort - 1;
                //减小最近100条记录的排序值
                \DB::table('articles')->where('category_id', $select->category_id)
                    ->where('sort', '<', $place->sort)
                    ->orderBy('sort', 'desc')
                    ->limit(100)
                    ->decrement('sort');
            } else {
                //上移
                $select->sort = $place->sort + 1;
                //增大最近100条记录的排序值
                \DB::table('articles')->where('category_id', $select->category_id)
                    ->where('sort', '>', $place->sort)
                    ->orderBy('sort', 'asc')
                    ->limit(100)
                    ->increment('sort');
            }

            $select->save();
        } catch (\Exception $e) {
            return Response::json([
                'code' => 500,
                'message' => $e->getMessage(),
            ]);
        }

        return Response::json([
            'code' => 200,
            'message' => 'success',
        ]);
    }

    public static function isRepetition($categoryId, $title, $id = null)
    {
        $result = self::where([
            'category_id' => $categoryId,
            'title' => $title,
        ]);
        if($id) {
            $result = $result->where('id', '!=', $id);
        }
        return $result->first() ? true : false;
    }
}
